﻿using System;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Diagnostics;
using System.IO;

namespace freedns.afraid.org
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        
        string direct_url = string.Empty;
        bool start_update_after_program_runs = false;
        bool start_minimized = true;
        const string config_file = "config.txt";

        private void buttonBrowseLogFile_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBoxLogFilePath.Text = saveFileDialog1.FileName;
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start("http://freedns.afraid.org/dynamic/");
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {            
            timerUpdate.Stop();
            buttonStop.Enabled = false;
            buttonStart.Enabled = true;
        }

        private void buttonSaveSettings_Click(object sender, EventArgs e)
        {
            StreamWriter sw = new StreamWriter(config_file, false, Encoding.GetEncoding("windows-1251"));
            sw.WriteLine("log=" + "\"" + textBoxLogFilePath.Text + "\"");
            sw.WriteLine("directurl_filepath=" + "\"" + textBoxDirectURLFilePath.Text + "\"");
            sw.WriteLine("directurl=" + "\"" + direct_url + "\"");
            sw.WriteLine("update_interval=" + "\"" + numericUpDownUpdateInterval.Value.ToString() + "\"");
            sw.WriteLine("start_update_after_program_runs=" + "\"" + start_update_after_program_runs.ToString() + "\"");
            sw.Write("start_minimized=" + "\"" + start_minimized.ToString() + "\"");
            sw.Close();
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {            
            timerUpdate.Interval = 1000;
            timerUpdate.Start();
            buttonStart.Enabled = false;
            buttonStop.Enabled = true;
        }

        private void buttonBrowseDirectURLFile_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                StreamReader sr = new StreamReader(textBoxDirectURLFilePath.Text, Encoding.GetEncoding("windows-1251"));
                direct_url = sr.ReadLine().Trim();
                textBoxDirectURLFilePath.Text = openFileDialog1.FileName;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            StreamReader sr = new StreamReader(config_file, Encoding.GetEncoding("windows-1251"));
            string[] config_lines = sr.ReadToEnd().Split('\n');
            for (int i = 0; i < config_lines.Length; i++)
            {
                string[] config_tmp = config_lines[i].Split('"');
                if (i == 0)
                    textBoxLogFilePath.Text = config_tmp[1];
                else if (i == 1)
                    textBoxDirectURLFilePath.Text = config_tmp[1];
                else if (i == 2)
                    direct_url = config_tmp[1];
                else if (i == 3)
                {
                    numericUpDownUpdateInterval.Value = Convert.ToInt32(config_tmp[1]);
                    timerUpdate.Interval = MinutesToMiliseconds(Convert.ToInt32(numericUpDownUpdateInterval.Value));
                }
                else if (i == 4)
                {
                    start_update_after_program_runs = Convert.ToBoolean(config_tmp[1]);
                    checkBoxStartUpdateAfterProgramRuns.Checked = start_update_after_program_runs;
                }
                else if (i == 5)
                {
                    start_minimized = Convert.ToBoolean(config_tmp[1]);
                    checkBoxStartMinimized.Checked = start_minimized;
                }
            }
            sr.Close();
            if (start_update_after_program_runs)
            {
                buttonStart.Enabled = false;
                timerUpdate.Interval = 1000;
                timerUpdate.Start();
            }
            if (start_minimized)
                this.WindowState = FormWindowState.Minimized;
        }

        int tick = 1;
        private void timerUpdate_Tick(object sender, EventArgs e)
        {
            if (tick == 1)
            {
                timerUpdate.Interval = MinutesToMiliseconds(Convert.ToInt32(numericUpDownUpdateInterval.Value));
                tick++;
            }            
            WebRequest request = WebRequest.Create(direct_url);
            Stream resp_stream = request.GetResponse().GetResponseStream();
            StreamReader sr = new System.IO.StreamReader(resp_stream);
            string resp_string = sr.ReadToEnd();
            StreamWriter sw = new System.IO.StreamWriter(textBoxLogFilePath.Text, true, Encoding.GetEncoding("windows-1251"));
            sw.WriteLine(System.DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + ": " + resp_string);
            sw.Close();
        }

        int MinutesToMiliseconds(int minutes)
        {
            int ms = minutes * 60000;
            return ms;
        }

        private void checkBoxStartUpdateAfterProgramRuns_CheckedChanged(object sender, EventArgs e)
        {
            start_update_after_program_runs = checkBoxStartUpdateAfterProgramRuns.Checked;
        }

        private void checkBoxStartMinimized_CheckedChanged(object sender, EventArgs e)
        {
            start_minimized = checkBoxStartMinimized.Checked;
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)            
                this.ShowInTaskbar = false;            
            else if (this.WindowState == FormWindowState.Normal)
                this.ShowInTaskbar = true;
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {            
            if (e.Button.ToString() == "Left")
            {
                if (this.WindowState == FormWindowState.Minimized)
                    this.WindowState = FormWindowState.Normal;
                else if (this.WindowState == FormWindowState.Normal)
                    this.WindowState = FormWindowState.Minimized;
            }
        }

        private void выйтиToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}